package com.smartaccounting.service;

import com.smartaccounting.dao.ExpenseDAO;
import com.smartaccounting.dao.IncomeDAO;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FinancialAnalysisService {
    private IncomeService incomeService;
    private ExpenseService expenseService;
    private BudgetService budgetService;

    public FinancialAnalysisService() {
        this.incomeService = new IncomeService();
        this.expenseService = new ExpenseService();
        this.budgetService = new BudgetService();
    }

    public Map<String, Object> getFinancialSummary(int userId, String monthYear) throws SQLException {
        Map<String, Object> summary = new HashMap<>();

        BigDecimal totalIncome = incomeService.getTotalIncomeByMonth(userId, monthYear);
        BigDecimal totalExpense = expenseService.getTotalExpenseByMonth(userId, monthYear);
        BigDecimal totalBudget = budgetService.getTotalBudgetByMonth(userId, monthYear);

        summary.put("totalIncome", totalIncome);
        summary.put("totalExpense", totalExpense);
        summary.put("totalBudget", totalBudget);
        summary.put("balance", totalIncome.subtract(totalExpense));
        summary.put("savingsRate", totalIncome.compareTo(BigDecimal.ZERO) > 0 ?
                totalIncome.subtract(totalExpense).divide(totalIncome, 4, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100)) :
                BigDecimal.ZERO);

        return summary;
    }

    public Map<String, BigDecimal> getBudgetVsActual(int userId, String monthYear) throws SQLException {
        Map<String, BigDecimal> comparison = new HashMap<>();

        List<Object[]> expenseSummary = expenseService.getExpenseCategorySummary(userId, monthYear);

        for (Object[] expense : expenseSummary) {
            String category = (String) expense[0];
            BigDecimal actualAmount = (BigDecimal) expense[1];

            Budget budget = budgetService.getBudgetByCategoryAndMonth(userId, category, monthYear);
            BigDecimal budgetAmount = budget != null ? budget.getAmount() : BigDecimal.ZERO;

            comparison.put(category + "_budget", budgetAmount);
            comparison.put(category + "_actual", actualAmount);
            comparison.put(category + "_difference", budgetAmount.subtract(actualAmount));
        }

        return comparison;
    }
}